package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 陈辉
 * @data 2023 14:31
 */
@Component
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor{

    //请求过滤方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
//        log.info("拦截到请求，本次登录用户id为：{}",userId);

        if (userId != null) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.parseInt(userId));
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }

    //响应过滤方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //注意： 当线程使用完数据，一定要记得清空ThreadLocal，避免引发：OutOfMemery 内存溢出问题。
        WmThreadLocalUtil.clear();
    }
}
